package org.jeecg.modules.wms.inventory.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.wms.config.WarehouseDictEnum;
import org.jeecg.modules.wms.goods.entity.WmsProducts;
import org.jeecg.modules.wms.goods.service.IWmsProductsService;
import org.jeecg.modules.wms.inventory.entity.WmsInventory;
import org.jeecg.modules.wms.inventory.entity.WmsInventoryTrans;
import org.jeecg.modules.wms.inventory.mapper.WmsInventoryTransMapper;
import org.jeecg.modules.wms.inventory.service.IWmsInventoryService;
import org.jeecg.modules.wms.inventory.service.IWmsInventoryTransService;
import org.jeecg.modules.wms.inventory.vo.WmsInventoryTransParam;
import org.jeecg.modules.wms.wmstask.entity.WmsTasks;
import org.jeecg.modules.wms.wmstask.entity.WmsTasksRecords;
import org.jeecg.modules.wms.wmstask.service.IWmsTasksRecordsService;
import org.jeecg.modules.wms.wmstask.service.IWmsTasksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 收货库存变更类
 */
@Service("wmsInventoryTransByReceiving")
public class WmsInventoryTransByReceiving extends ServiceImpl<WmsInventoryTransMapper, WmsInventoryTrans> implements IWmsInventoryTransService {

    @Autowired
    private IWmsInventoryService inventoryService;

    @Autowired
    private IWmsTasksRecordsService tasksRecordsService ;
    @Autowired
    private IWmsProductsService productsService;

    // 收货业务
    @Override
    public void transInventory(WmsInventoryTransParam param) {
        //1、参数校验：全局唯一需要的参数，还有业务需要的必要信息（储位编码、商品id、是否可售、执行数量...）
        if (ObjectUtil.isNull(param) ||
                ObjectUtil.isNull(param.getProductId()) ||
                ObjectUtil.isNull(param.getTargetLocationCode()) ||
                ObjectUtil.isNull(param.getIsSellable()) ||
                ObjectUtil.isNull(param.getExecQuantity())) {
            throw new RuntimeException("参数错误");
        }
        //查询库存唯一
        WmsInventory inventory = inventoryService.getInventoryByUniqueKey(
                param.getProductId(),
                param.getTargetLocationCode(),
                param.getBatchNumber());

        if (ObjectUtil.isNull(inventory)) {
            inventory = new WmsInventory();
            inventory.setStockQuantity(0);
            inventory.setAvailableQuantity(0);
            BeanUtil.copyProperties(param, inventory);
            inventory.setLocationCode(param.getTargetLocationCode());
            inventory.setStockQuantity(inventory.getStockQuantity() + param.getExecQuantity());
            if ("1".equals(param.getIsSellable())) {
                //可用数量
                inventory.setAvailableQuantity(inventory.getAvailableQuantity() + param.getExecQuantity());
            }
            //更新时间
            inventory.setCreateTime(new Date());
            inventory.setUpdateTime(new Date());
            //货主id、入库时间、保质期-->任务表中（唯一键：商品id+储位编码+批次+任务类型）
            inventory.setOwnerId(this.getOwnerId(param.getProductId()));
            WmsTasksRecords records = this.getTaskById(param.getProductId(), param.getTargetLocationCode(), param.getBatchNumber());
            inventory.setStockInTime(records.getOperationTime());
            inventory.setExpiryDate(records.getExpiryDate());


            try {
                inventoryService.save(inventory);
            } catch (Exception e) {
                throw new JeecgBootException("库存保存失败");
            }
        }


        if (ObjectUtil.isNotNull(inventory)) {
            //在库数量
            inventory.setStockQuantity(inventory.getStockQuantity() + param.getExecQuantity());
            if ("1".equals(param.getIsSellable())) {
                //可用数量
                inventory.setAvailableQuantity(inventory.getAvailableQuantity() + param.getExecQuantity());
            }
            //更新时间
            inventory.setUpdateTime(new Date());
            try {
                inventoryService.updateById(inventory);
            } catch (Exception e) {
                throw new JeecgBootException("库存更新失败");
            }
        }

        //记录库存变更记录
        WmsInventoryTrans trans = new WmsInventoryTrans();
        BeanUtil.copyProperties(param, trans);
        trans.setLocationCode(param.getTargetLocationCode());
        trans.setCreateTime(new Date());
        trans.setChangeQuantity(param.getExecQuantity());
        trans.setTransactionType(WarehouseDictEnum.INVENTORY_RECEIVING.getCode());
        //变更时间为任务执行时间
        trans.setTransactionTime(this.getTaskById(param.getProductId(), param.getTargetLocationCode(), param.getBatchNumber()).getOperationTime());
        try {
            this.save(trans);
        } catch (Exception e) {
            throw new JeecgBootException("库存变更记录保存失败");
        }
    }


    private WmsTasksRecords getTaskById(String productId, String locationCode, String batchNumber) {

        return tasksRecordsService.getOne(Wrappers.lambdaQuery(WmsTasksRecords.class)
                .eq(WmsTasksRecords::getProductId, productId)
                .eq(WmsTasksRecords::getTargetLocationCode, locationCode)
                .eq(ObjectUtil.isNotEmpty(batchNumber), WmsTasksRecords::getBatchNumber, batchNumber)
                .isNull(ObjectUtil.isEmpty(batchNumber), WmsTasksRecords::getBatchNumber)
        );
    }

    private String getOwnerId(String productId) {
        return productsService.getOne(Wrappers.lambdaQuery(WmsProducts.class)
                .eq(WmsProducts::getId, productId)
        ).getOwnerId();
    }
}
